package org.example.innovate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import com.hankcs.hanlp.seg.Other.DoubleArrayTrieSegment;
import com.hankcs.hanlp.seg.common.Term;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.example.innovate.common.CommonResponse;
import org.example.innovate.domain.*;
import org.example.innovate.mapper.*;
import org.example.innovate.service.DishService;
import org.example.innovate.util.JwtUtil;
import org.example.innovate.util.OssUpload;
import org.example.innovate.vo.*;
import org.springframework.stereotype.Service;
import org.example.innovate.dto.PageDTO;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.Collections;
import java.util.stream.Collectors;

/**
* @author 马鑫
* @description 针对表【dish】的数据库操作Service实现
* @createDate 2024-12-28 22:32:27
*/
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
    implements DishService{
    @Resource
    private DishMapper dishMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RecipeMapper recipeMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private MyPostMapper myPostMapper;
    @Resource
    private CollectionMapper collectionMapper;
    @Resource
    private FollowMapper followMapper;
    @Resource
    private PostViewMapper postViewMapper;
    @Resource
    private HistoryMapper historyMapper;

    // 权重和时间衰减因子
    private static final double RAN_WEIGHT=1.1;
    private static final double LIKE_WEIGHT = 1.5;
    private static final double FAV_WEIGHT = 2.0;
    private static final double VIEW_WEIGHT = 0.5;
    private static final double DECAY_RATE = 0.1; // 每小时衰减率

    @Override
    public CommonResponse<String> updateData() throws JSONException {
        System.out.println(123);
        int num=1;
        while (true)
        {
            QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dish_id",num);
            Dish dish=dishMapper.selectOne(queryWrapper);
            if(dish==null)
            {
                break;
            }
            int like=dish.getLikes();
            int fav=dish.getFavorites();
            int view=dish.getViews();
            Random random = new Random();
            int ran = random.nextInt(500);
            Date date=dish.getUpdatedAt();
            Instant instant=date.toInstant();
            long timeDiffHours = ChronoUnit.DAYS.between(instant, Instant.now());

            // 加权求和
            double rawScore = (like * LIKE_WEIGHT +
                    fav * FAV_WEIGHT +
                    view * VIEW_WEIGHT +
                    ran * RAN_WEIGHT);

            // 应用时间衰减
            double decayedScore = rawScore * Math.exp(-DECAY_RATE * timeDiffHours);
            BigDecimal bigDecimalValue = new BigDecimal(decayedScore);
            BigDecimal formattedValue = bigDecimalValue.setScale(10, RoundingMode.HALF_UP);
            BigDecimal increment = new BigDecimal("0.1");
            formattedValue=formattedValue.add(increment);
            Object jsondata=dish.getNutritionInfo();
            JSONObject tagJson = null;
            if (!(jsondata instanceof JSONObject)) {
                tagJson = new JSONObject();
            } else {
                tagJson = (JSONObject) jsondata;
            }
            // 更新JSON对象
            tagJson.put("value", formattedValue);

            // 将JSON对象序列化为字符串
            String jsonString = tagJson.toString();
            dish.setNutritionInfo(jsonString);
            dishMapper.updateById(dish);
            num++;
        }
        return CommonResponse.createForSuccess("更新成功");
    }

    @Override
    public CommonResponse<DishVo> getHotDish(PageDTO pageDTO) throws JSONException {
//        if(pageDTO.getPage()==1)
//        {
//            updateData();
////        }
//        Date now = Date.from(Instant.now());
//        System.out.println(now);
        Page<Dish> page=new Page<>(pageDTO.getPage(),pageDTO.getLimit());
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        queryWrapper.apply("CAST(JSON_EXTRACT(nutrition_info, '$.value') AS DECIMAL(10, 2)) IS NOT NULL")
                .orderByDesc("CAST(JSON_EXTRACT(nutrition_info, '$.value') AS DECIMAL(10, 2))");
        List<Dish> dishList=dishMapper.selectPage(page,queryWrapper).getRecords();
        List<DishOneVo> dishOneVos=new ArrayList<>();
        for(Dish dish:dishList)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",dish.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);
            DishOneVo dishOneVo=new DishOneVo();
            dishOneVo.setUsername(user.getUsername());
            Calendar cal = Calendar.getInstance();
            cal.setTime(dish.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            Date eightHoursAgo = cal.getTime();
            dish.setCreatedAt(eightHoursAgo);
            cal.setTime(dish.getUpdatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            dish.setUpdatedAt(eightHoursAgo);
            dishOneVo.setDish(dish);
            dishOneVos.add(dishOneVo);
        }
        DishVo dishVo=new DishVo();
        dishVo.setDishes(dishOneVos);
        int total= Math.toIntExact(dishMapper.selectCount(queryWrapper));
        dishVo.setTotal(total);
        return CommonResponse.createForSuccess("查询成功",dishVo);
    }

    @Override
    public CommonResponse<DishVo> getPersonDish(PageDTO pageDTO,HttpServletRequest request) throws JSONException {
        String token=request.getHeader("token");
        JwtUtil.verifyToken(token);
        User user0=JwtUtil.getCurrentUser(token);
        if(user0==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        Date date=user0.getCreatedAt();
        Instant instant=date.toInstant();
        long timeDiffHours = ChronoUnit.DAYS.between(instant, Instant.now());
        String completeJsonPath = "$.\"" + user0.getUserId() + "\"";
        Page<Dish> page=new Page<>(pageDTO.getPage(),pageDTO.getLimit());
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        if(timeDiffHours>1)
        {
            queryWrapper.last(
                    "WHERE CAST(JSON_EXTRACT(tag, '" + completeJsonPath + "') AS DECIMAL(10, 2)) IS NOT NULL " +
                            "ORDER BY CAST(JSON_EXTRACT(tag, '" + completeJsonPath + "') AS DECIMAL(10, 2)) DESC"
            );
        }
        else {
            System.out.println("新用户");
            queryWrapper.apply("CAST(JSON_EXTRACT(tag, '$.\"100004\"') AS DECIMAL(10, 2)) IS NOT NULL")
                    .orderByDesc("CAST(JSON_EXTRACT(tag, '$.\"100004\"') AS DECIMAL(10, 2))");
        }
        List<Dish> dishList=dishMapper.selectPage(page,queryWrapper).getRecords();
        List<DishOneVo> dishOneVos=new ArrayList<>();
        for(Dish dish:dishList)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",dish.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);
            DishOneVo dishOneVo=new DishOneVo();
            dishOneVo.setUsername(user.getUsername());
            Calendar cal = Calendar.getInstance();
            cal.setTime(dish.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            Date eightHoursAgo = cal.getTime();
            dish.setCreatedAt(eightHoursAgo);
            cal.setTime(dish.getUpdatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            dish.setUpdatedAt(eightHoursAgo);
            dishOneVo.setDish(dish);
            dishOneVos.add(dishOneVo);
        }
        DishVo dishVo=new DishVo();
        dishVo.setDishes(dishOneVos);
        int total= Math.toIntExact(dishMapper.selectCount(queryWrapper));
        dishVo.setTotal(total);
        return CommonResponse.createForSuccess("查询成功",dishVo);
    }


    @Override
    public CommonResponse<DishBodyVo> getdishBody(Dish dish,HttpServletRequest request) throws IOException {
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",dish.getDishId());
        Dish dish1=dishMapper.selectOne(queryWrapper);
        Calendar cal = Calendar.getInstance();
        cal.setTime(dish1.getCreatedAt());
        cal.add(Calendar.HOUR_OF_DAY, 8);
        Date eightHoursAgo = cal.getTime();
        dish1.setCreatedAt(eightHoursAgo);
        cal.setTime(dish1.getUpdatedAt());
        cal.add(Calendar.HOUR_OF_DAY, 8);
        eightHoursAgo = cal.getTime();
        dish1.setUpdatedAt(eightHoursAgo);
        URL url = new URL(dish1.getDescriptionUrl());
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        List<String> bodyList=new ArrayList<>();
        List<String> materials=new ArrayList<>();
        int num=1;
        String body="";
        String line;
        while ((line = reader.readLine()) != null) {
            if(num==3&&!line.equals("*****"))
            {
                materials.add(line);
            }
            else if(num==4){
                body+=line;
                if (Character.isDigit(line.charAt(0)))
                {
                    bodyList.add(body);
                    body="";
                }
            }
            if(line.equals("*****"))
            {
                num++;
            }
        }
        reader.close();
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("user_id",dish1.getUserId());
        User user=userMapper.selectOne(userQueryWrapper);
        List<Recipe> recipes;
        QueryWrapper<Recipe> recipeQueryWrapper=new QueryWrapper<>();
        recipeQueryWrapper.eq("dish_id",dish1.getDishId());
        recipes=recipeMapper.selectList(recipeQueryWrapper);
        for (Recipe recipe : recipes) {
            cal.setTime(recipe.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            recipe.setCreatedAt(eightHoursAgo);
            cal.setTime(recipe.getUpdatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            recipe.setUpdatedAt(eightHoursAgo);
        }
        DishBodyVo dishBodyVo=new DishBodyVo();
        dishBodyVo.setDish(dish1);
        dishBodyVo.setBody(bodyList);
        dishBodyVo.setMaterial(materials);
        dishBodyVo.setUsername(user.getUsername());
        dishBodyVo.setRecipes(recipes);
        List<Comment> comments_temp;
        QueryWrapper<Comment> commentQueryWrapper=new QueryWrapper<>();
        commentQueryWrapper.eq("foreign_id",dish.getDishId());
        commentQueryWrapper.eq("reply",0);
        comments_temp=commentMapper.selectList(commentQueryWrapper);
        List<CommentVo> comments=new ArrayList<>();
        for(Comment comment:comments_temp){
            QueryWrapper<User> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("user_id",comment.getUserId());
            User user1=userMapper.selectOne(queryWrapper1);
            CommentVo commentVo=new CommentVo();
            commentVo.setName(user1.getUsername());
            commentVo.setId(user1.getUserId());
            commentVo.setContent(comment.getContent());
            commentVo.setLikes(comment.getLikes());
            commentVo.setComment_id(comment.getCommentId());
            cal.setTime(comment.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            commentVo.setTime(eightHoursAgo);
            List<CommentVo> commentVoList=new ArrayList<>();
            QueryWrapper<Comment> commentQueryWrapper1=new QueryWrapper<>();
            commentQueryWrapper1.eq("foreign_id",comment.getCommentId());
            commentQueryWrapper1.eq("reply",1);
            comments_temp=commentMapper.selectList(commentQueryWrapper1);
            for(Comment comment1:comments_temp){
                QueryWrapper<User> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("user_id",comment1.getUserId());
                User user2=userMapper.selectOne(queryWrapper2);
                CommentVo commentVo1=new CommentVo();
                commentVo1.setName(user2.getUsername());
                commentVo1.setId(user2.getUserId());
                commentVo1.setContent(comment1.getContent());
                commentVo1.setLikes(comment1.getLikes());
                commentVo1.setComment_id(comment1.getCommentId());
                Calendar cal1 = Calendar.getInstance();
                cal1.setTime(comment1.getCreatedAt());
                cal1.add(Calendar.HOUR_OF_DAY, 8);
                Date eightHoursAgo1 = cal1.getTime();
                commentVo1.setTime(eightHoursAgo1);
                commentVoList.add(commentVo1);
            }
            commentVo.setComments(commentVoList);
            comments.add(commentVo);
        }
        dishBodyVo.setComments(comments);
        String token=request.getHeader("token");
        JwtUtil.verifyToken(token);
        User user0= JwtUtil.getCurrentUser(token);
        if(user0==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        QueryWrapper<org.example.innovate.domain.Collections> collectionsQueryWrapper=new QueryWrapper<>();
        collectionsQueryWrapper.eq("post_id",dish.getDishId());
        collectionsQueryWrapper.eq("user_id",user0.getUserId());
        org.example.innovate.domain.Collections collections=collectionMapper.selectOne(collectionsQueryWrapper);
        dishBodyVo.setCollect(collections != null);
        QueryWrapper<Follow> followQueryWrapper=new QueryWrapper<>();
        followQueryWrapper.eq("follower_id",user0.getUserId());
        followQueryWrapper.eq("followed_id",user.getUserId());
        Follow follow=followMapper.selectOne(followQueryWrapper);
        dishBodyVo.setFollow(follow != null);
        QueryWrapper<User> userQueryWrapper1=new QueryWrapper<>();
        userQueryWrapper1.eq("user_id",dish1.getUserId());
        dishBodyVo.setProfilePicture(userMapper.selectOne(userQueryWrapper1).getProfilePicture());
        return CommonResponse.createForSuccess("查询成功",dishBodyVo);
    }


    // 双向同义词映射
    private static final Map<String, Set<String>> synonyms = new HashMap<>();
    private static final Map<String, String> reverseSynonyms = new HashMap<>();

    static {
        // 初始化自定义同义词对
        addSynonymPair("西红柿", "番茄");
        addSynonymPair("鸡蛋", "蛋");
    }

    /**
     * 添加一对同义词。
     */
    public static void addSynonymPair(String word1, String word2) {
        addSynonym(word1, word2);
        addSynonym(word2, word1);
    }

    /**
     * 单向添加同义词关系。
     */
    private static void addSynonym(String original, String synonym) {
        synonyms.computeIfAbsent(original, k -> new HashSet<>()).add(synonym);
        reverseSynonyms.put(synonym, original);
    }

    /**
     * 根据自定义同义词库扩展给定的词语列表，并生成所有合理的组合。
     */
    public List<String> expand(List<String> tokens) {
        List<List<String>> expandedTokensList = new ArrayList<>();
        for (String token : tokens) {
            Set<String> alternatives = new HashSet<>(synonyms.getOrDefault(token, Collections.emptySet()));
            alternatives.add(token); // 包含原词
            expandedTokensList.add(new ArrayList<>(alternatives));
        }

        return generateCombinations(expandedTokensList);
    }

    /**
     * 递归生成所有可能的组合。
     */
    private List<String> generateCombinations(List<List<String>> lists) {
        List<String> combinations = new ArrayList<>();
        generateCombinationsHelper(lists, 0, "", combinations);
        return combinations;
    }

    private void generateCombinationsHelper(List<List<String>> lists, int index, String current, List<String> combinations) {
        if (index == lists.size()) {
            combinations.add(current.trim());
            return;
        }

        for (String item : lists.get(index)) {
            generateCombinationsHelper(lists, index + 1, current + item, combinations);
        }
    }

    @Override
    public CommonResponse<List<DishOneVo>> search(String content,HttpServletRequest request) throws IOException {
        String token=request.getHeader("token");
        JwtUtil.verifyToken(token);
        User user_1= JwtUtil.getCurrentUser(token);
        if(user_1==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        History history=new History();
        history.setUserId(user_1.getUserId());
        history.setContent(content);
        historyMapper.insert(history);
        InputStreamReader inStream0 = new InputStreamReader(new FileInputStream("src/main/resources/static/dictory.txt"), StandardCharsets.UTF_8);
        BufferedReader bf0 = new BufferedReader(inStream0);
        String a=null;
        while((a=bf0.readLine())!=null){
            CustomDictionary.add(a);
        }
        DoubleArrayTrieSegment segment = new DoubleArrayTrieSegment();
        List<Term> terms = segment.seg(content);
        // 测试词语列表扩展功能
        List<String> inputTokens = new ArrayList<>();
        for (Term term : terms) {
            inputTokens.add(term.word);
        }
        List<String> contents = expand(inputTokens);
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("CAST(JSON_EXTRACT(nutrition_info, '$.value') AS DECIMAL(10, 0)) IS NOT NULL")
                .orderByDesc("CAST(JSON_EXTRACT(nutrition_info, '$.value') AS DECIMAL(10, 0))");
        List<Dish> allDishes = dishMapper.selectList(queryWrapper);
        List<Dish> dishes = new ArrayList<>();
        List<Dish> Other_dishes=new ArrayList<>();
        for (Dish dish:allDishes)
        {
            boolean x=false;
            for(String content1:contents)
            {
                if (dish.getName().contains(content1))
                {
                    x=true;
                    dishes.add(dish);
                    System.out.println(dish.getName());
                    break;
                }
            }
            if (!x)
            {
                Other_dishes.add(dish);
            }
        }
        if(dishes.size()<5)
        {
            List<Dish> toRemove = new ArrayList<>();
            String pinyin = HanLP.convertToPinyinString(content, "", true);
            for (Dish dish:Other_dishes)
            {
                String target = HanLP.convertToPinyinString(dish.getName(), "", true);
                if(target.contains(pinyin))
                {
                    dishes.add(dish);
                    toRemove.add(dish);
                }
            }
            dishes.removeAll(toRemove);
        }
        List<DishOneVo> dishOneVos=new ArrayList<>();
        for(Dish dish:dishes)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",dish.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);
            DishOneVo dishOneVo=new DishOneVo();
            dishOneVo.setUsername(user.getUsername());
            Calendar cal = Calendar.getInstance();
            cal.setTime(dish.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            Date eightHoursAgo = cal.getTime();
            dish.setCreatedAt(eightHoursAgo);
            cal.setTime(dish.getUpdatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            dish.setUpdatedAt(eightHoursAgo);
            dishOneVo.setDish(dish);
            dishOneVos.add(dishOneVo);
        }
        return CommonResponse.createForSuccess("搜索成功",dishOneVos);
    }

    @Override
    public CommonResponse<List<DishOneVo>> getCategory(String category){
        List<Dish> dishes=new ArrayList<>();
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("CAST(JSON_EXTRACT(nutrition_info, '$.value') AS DECIMAL(10, 2)) IS NOT NULL")
                .orderByDesc("CAST(JSON_EXTRACT(nutrition_info, '$.value') AS DECIMAL(10, 2))");
        List<Dish> allDishes = dishMapper.selectList(queryWrapper);
        for (Dish dish:allDishes)
        {
            if(dish.getCategory().contains(category))
            {
                dishes.add(dish);
            }
        }
        List<DishOneVo> dishOneVos=new ArrayList<>();
        for(Dish dish:dishes)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",dish.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);
            DishOneVo dishOneVo=new DishOneVo();
            dishOneVo.setUsername(user.getUsername());
            Calendar cal = Calendar.getInstance();
            cal.setTime(dish.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            Date eightHoursAgo = cal.getTime();
            dish.setCreatedAt(eightHoursAgo);
            cal.setTime(dish.getUpdatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            dish.setUpdatedAt(eightHoursAgo);
            dishOneVo.setDish(dish);
            dishOneVos.add(dishOneVo);
        }
        return CommonResponse.createForSuccess("查询成功",dishOneVos);
    }

    @Override
    public CommonResponse<uploadVo> upload(List<MultipartFile> images, uploadVo up, String token) throws IOException {
        MultipartFile image= images.get(0);
        MultipartFile[] step_image=new MultipartFile[images.size()-1];
        for (int i=1;i<images.size();i++)
        {
            step_image[i-1]=images.get(i);
        }
        String num= String.valueOf(dishMapper.selectCount(null)+1);
        UUID uuid = UUID.randomUUID();
        String filePath = "src/main/resources/static/file/"+uuid+".txt";
        Path path = Paths.get(filePath);
        Files.createFile(path);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(up.getName());
            writer.newLine();
            writer.write("*****");
            writer.newLine();
            for (String a:up.getCategory())
            {
                writer.write(a);
                writer.newLine();
            }
            writer.write("*****");
            writer.newLine();
            for (String a:up.getMaterial())
            {
                writer.write(a);
                writer.newLine();
            }
            writer.write("*****");
            writer.newLine();
            for (String a:up.getStep())
            {
                writer.write(a);
                writer.newLine();
            }
            writer.write("*****");
        }
        JwtUtil.verifyToken(token);
        User user= JwtUtil.getCurrentUser(token);
        if(user==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        Dish dish=new Dish();
        dish.setName(up.getName());
        dish.setUserId(user.getUserId());
        String category="";
        for(String a:up.getCategory())
        {
            category+=a;
            category+=",";
        }
        dish.setCategory(category);
        String baseurl="https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/";
        String url="food_moment_discover/train/data/"+num+"/menu.txt";
        dish.setDescriptionUrl(baseurl+url);
        OssUpload.load(filePath,url);
        String Ossurl=image.getOriginalFilename();
        Ossurl=FilenameUtils.getExtension(Ossurl);
        String image_url=num+"/main."+Ossurl;
        Ossurl="food_moment_discover/train/data/"+num+"/main."+Ossurl;
        OssUpload.publishImgToOSS(image,Ossurl);
        dish.setImageUrl(image_url);
        dish.setLikes(0);
        dish.setViews(0);
        dish.setFavorites(0);
        dishMapper.insert(dish);
        MyPost myPost=new MyPost();
        myPost.setId(Integer.valueOf(num));
        myPost.setUserId(user.getUserId());
        myPost.setTitle(up.getName());
        myPost.setContent(image_url);
        myPostMapper.insert(myPost);
        System.out.println(11111+num);
        for(int i=0;i<step_image.length;i++)
        {
            Ossurl=step_image[i].getOriginalFilename();
            Ossurl=FilenameUtils.getExtension(Ossurl);
            Recipe recipe=new Recipe();
            recipe.setDishId(Integer.valueOf(num));
            image_url=num+"/"+up.getNum()[i]+"."+Ossurl;
            recipe.setImageUrl(image_url);
            recipeMapper.insert(recipe);
            Ossurl="food_moment_discover/train/data/"+num+"/"+ up.getNum()[i] +"."+Ossurl;
            OssUpload.publishImgToOSS(step_image[i],Ossurl);
        }
        return CommonResponse.createForSuccess("上传成功",up);
    }

    @Override
    public CommonResponse<DishVo> getDishByUserId(Integer userId, PageDTO pageDTO) {
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("user_id", userId);
        Page<Dish> page=new Page<>(pageDTO.getPage(),pageDTO.getLimit());
        List<Dish> dishes=dishMapper.selectPage(page,dishQueryWrapper).getRecords();

        if (dishes != null && !dishes.isEmpty()) {
            List<DishOneVo> dishOneVos = new ArrayList<>();

            for (Dish dish : dishes) {
                DishOneVo dishOneVo = new DishOneVo();
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("user_id", dish.getUserId());
                User user = userMapper.selectOne(userQueryWrapper);
                dishOneVo.setUsername(user.getUsername());
                Calendar cal = Calendar.getInstance();
                cal.setTime(dish.getCreatedAt());
                cal.add(Calendar.HOUR_OF_DAY, 8);
                Date eightHoursAgo = cal.getTime();
                dish.setCreatedAt(eightHoursAgo);
                cal.setTime(dish.getUpdatedAt());
                cal.add(Calendar.HOUR_OF_DAY, 8);
                eightHoursAgo = cal.getTime();
                dish.setUpdatedAt(eightHoursAgo);
                dishOneVo.setDish(dish);
                dishOneVos.add(dishOneVo);
            }

            DishVo dishVo = new DishVo();
            int total= Math.toIntExact(dishMapper.selectCount(dishQueryWrapper));
            dishVo.setDishes(dishOneVos);
            dishVo.setTotal(total);

            return CommonResponse.createForSuccess("查询成功", dishVo);
        }
        else{
            return CommonResponse.createForError("用户没有上传过菜品");
        }
    }

    @Override
    public CommonResponse<BackVo> setBack(BackVo backVo,HttpServletRequest request) {
        if(backVo.getId()<1)
        {
            return CommonResponse.createForError();
        }
        String token=request.getHeader("token");
        System.out.println(token);
        JwtUtil.verifyToken(token);
        User user= JwtUtil.getCurrentUser(token);
        if(user==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        if(backVo.getFavorite()>0)
        {
            org.example.innovate.domain.Collections collections=new org.example.innovate.domain.Collections();
            collections.setUserId(user.getUserId());
            collections.setPostId(backVo.getId());
            collectionMapper.insert(collections);
        }
        else if(backVo.getFavorite()<0){
            QueryWrapper<org.example.innovate.domain.Collections> collectionsQueryWrapper=new QueryWrapper<>();
            collectionsQueryWrapper.eq("user_id", user.getUserId());
            collectionsQueryWrapper.eq("post_id", backVo.getId());
            collectionMapper.delete(collectionsQueryWrapper);
        }
        PostView postView=new PostView();
        postView.setUserId(user.getUserId());
        postView.setPostId(backVo.getId());
        postViewMapper.insert(postView);

        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("dish_id", backVo.getId());
        Dish dish=dishMapper.selectOne(dishQueryWrapper);
        dish.setLikes(dish.getLikes()+backVo.getLike());
        dish.setViews(dish.getViews()+1);
        dish.setFavorites(dish.getFavorites()+backVo.getFavorite());
        dishMapper.updateById(dish);
        if(backVo.getFollow()>0)
        {
            Follow follow=new Follow();
            follow.setFollowerId(user.getUserId());
            follow.setFollowedId(dish.getUserId());
            followMapper.insert(follow);
        }
        else if(backVo.getFollow()<0)
        {
            QueryWrapper<Follow> followQueryWrapper=new QueryWrapper<>();
            followQueryWrapper.eq("follower_id", user.getUserId());
            followQueryWrapper.eq("followed_id", dish.getUserId());
            followMapper.delete(followQueryWrapper);
        }
        return CommonResponse.createForSuccess(backVo);
    }

    public CommonResponse<User> updateUser() throws IOException, JSONException {
        List<User> users=userMapper.selectList(null);
        for(User user:users)
        {
            QueryWrapper<PostView> postViewQueryWrapper=new QueryWrapper<>();
            postViewQueryWrapper.eq("user_id", user.getUserId());
            List<PostView> postViews=postViewMapper.selectList(postViewQueryWrapper);
            List<Dish> dish_view = new ArrayList<>();
            for (PostView postView : postViews) {
                Dish dish=dishMapper.selectById(postView.getPostId());
                dish_view.add(dish);
            }
            Map<String,Integer> values=new HashMap<>() ;
            int[] arr={0,0,0,0,0,0,0,0,0,0};
            for (Dish dish : dish_view) {
                if (dish.getCategory().contains("家常菜"))
                {
                    arr[0]++;
                }
                if (dish.getCategory().contains("煎"))
                {
                    arr[1]++;
                }
                if (dish.getCategory().contains("蒸"))
                {
                    arr[2]++;
                }
                if (dish.getCategory().contains("炖"))
                {
                    arr[3]++;
                }
                if (dish.getCategory().contains("红烧"))
                {
                    arr[4]++;
                }
                if (dish.getCategory().contains("炸"))
                {
                    arr[5]++;
                }
                if (dish.getCategory().contains("卤"))
                {
                    arr[6]++;
                }
                if (dish.getCategory().contains("干锅"))
                {
                    arr[7]++;
                }
                if (dish.getCategory().contains("火锅"))
                {
                    arr[8]++;
                }
                if (dish.getCategory().contains("免烤"))
                {
                    arr[9]++;
                }
                URL url = new URL(dish.getDescriptionUrl());
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                int num=1;
                String line;
                while ((line = reader.readLine()) != null) {
                    if(num==3&&!line.equals("*****"))
                    {
                        String[] parts = line.split("\\s+");
                        String ingredientName = parts[0];
                        values.merge(ingredientName,1,Integer::sum);
                    }
                    if(line.equals("*****"))
                    {
                        num++;
                    }
                }
                reader.close();
            }
            QueryWrapper<org.example.innovate.domain.Collections> collectionsQueryWrapper=new QueryWrapper<>();
            collectionsQueryWrapper.eq("user_id", user.getUserId());
            List<org.example.innovate.domain.Collections> collections=collectionMapper.selectList(collectionsQueryWrapper);
            List<Dish> dish_collections = new ArrayList<>();
            for (org.example.innovate.domain.Collections collection:collections) {
                Dish dish=dishMapper.selectById(collection.getPostId());
                dish_collections.add(dish);
            }
            for (Dish dish : dish_collections) {
                if (dish.getCategory().contains("家常菜"))
                {
                    arr[0]++;
                }
                if (dish.getCategory().contains("煎"))
                {
                    arr[1]++;
                }
                if (dish.getCategory().contains("蒸"))
                {
                    arr[2]++;
                }
                if (dish.getCategory().contains("炖"))
                {
                    arr[3]++;
                }
                if (dish.getCategory().contains("红烧"))
                {
                    arr[4]++;
                }
                if (dish.getCategory().contains("炸"))
                {
                    arr[5]++;
                }
                if (dish.getCategory().contains("卤"))
                {
                    arr[6]++;
                }
                if (dish.getCategory().contains("干锅"))
                {
                    arr[7]++;
                }
                if (dish.getCategory().contains("火锅"))
                {
                    arr[8]++;
                }
                if (dish.getCategory().contains("免烤"))
                {
                    arr[9]++;
                }
                URL url = new URL(dish.getDescriptionUrl());
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                int num=1;
                String line;
                while ((line = reader.readLine()) != null) {
                    if(num==3&&!line.equals("*****"))
                    {
                        String[] parts = line.split("\\s+");
                        String ingredientName = parts[0];
                        values.merge(ingredientName,1,Integer::sum);
                    }
                    if(line.equals("*****"))
                    {
                        num++;
                    }
                }
                reader.close();
            }
            int total=0;
            String ans="";
            for(int i=1;i<10;i++)
            {
                if(arr[i]>arr[0])
                {
                    arr[0]=arr[i];
                    total=i;
                }
            }
            switch (total)
            {
                case 0:ans="家常菜";
                break;
                case 1:ans="煎";
                break;
                case 2:ans="蒸";
                    break;
                case 3:ans="炖";
                    break;
                case 4:ans="红烧";
                    break;
                case 5:ans="炸";
                    break;
                case 6:ans="卤";
                    break;
                case 7:ans="干锅";
                    break;
                case 8:ans="火锅";
                    break;
                case 9:ans="免烤";
                    break;
            }
            List<Map.Entry<String, Integer>> topThreeEntries = values.entrySet().stream()
                    .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                    .limit(3)
                    .toList();

            Object jsondata=user.getPer();
            JSONObject tagJson = null;
            if (!(jsondata instanceof JSONObject)) {
                tagJson = new JSONObject();
            } else {
                tagJson = (JSONObject) jsondata;
            }
            // 更新JSON对象
            tagJson.put(ans,-1);

            for (Map.Entry<String, Integer> entry : topThreeEntries) {
                tagJson.put(entry.getKey(), entry.getValue());
            }
            // 将JSON对象序列化为字符串
            String jsonString = tagJson.toString();
            user.setPer(jsonString);
            userMapper.updateById(user);
        }
        List<Dish> dishList=dishMapper.selectList(null);
        for (Dish dish : dishList) {
            String jsonString = (String) dish.getNutritionInfo();
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Double> dishMap=mapper.readValue(jsonString, Map.class);
            Object jsondata=dish.getTag();
            JSONObject tagJson = null;
            if (!(jsondata instanceof JSONObject)) {
                tagJson = new JSONObject();
            } else {
                tagJson = (JSONObject) jsondata;
            }
            double value=dishMap.get("value");
            String meta="";
            URL url = new URL(dish.getDescriptionUrl());
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            int num=1;
            String line;
            while ((line = reader.readLine()) != null) {
                if(num==3&&!line.equals("*****"))
                {
                    String[] parts = line.split("\\s+");
                    if(parts.length>0)
                    {
                        meta+=parts[0]+",";
                    }
                }
                if(line.equals("*****"))
                {
                    num++;
                }
            }
            reader.close();
            List<User> userList=userMapper.selectList(null);
            for (User user : userList) {
                String jsonString1 = (String) user.getPer();
                ObjectMapper mapper1 = new ObjectMapper();
                Map<String,Integer> userMap=mapper1.readValue(jsonString1, Map.class);
                for (Map.Entry<String, Integer> entry : userMap.entrySet())
                {
                    if(entry.getValue()>=0)
                    {
                        if(meta.contains(entry.getKey()))
                        {
                            value=value+entry.getValue()*50;
                        }
                    }
                    else {
                        if(dish.getCategory().contains(entry.getKey()))
                        {
                            value=value+entry.getValue()*30;
                        }
                    }
                }
                tagJson.put(String.valueOf(user.getUserId()),value);
            }
            String jsonString1 = tagJson.toString();
            dish.setTag(jsonString1);
            dishMapper.updateById(dish);
        }
        return CommonResponse.createForSuccess();
    }

    @Override
    public CommonResponse<Integer> repair()
    {
        List<Dish> dishList=dishMapper.selectList(null);
        for (Dish dish : dishList) {
            Random random = new Random();
            int likes = random.nextInt(500);
            dish.setLikes(likes);
            int views = random.nextInt(500);
            dish.setViews(views);
            int favorites = random.nextInt(500);
            dish.setFavorites(favorites);
            dishMapper.updateById(dish);
        }
        return CommonResponse.createForSuccess();
    }
}




